<?php
/**
 * Created by PhpStorm.
 * User: s.utkin
 * Date: 13.01.2015
 * Time: 14:05
 */

namespace EmailDelivery\Workers;


use EmailDelivery\Queue\Worker;
use Pinenut\Mail;
use Pinenut\Queue\ProcessingQueue;

class SendTemplateAction extends Worker {
	/**
	 * @var null|Mail
	 */
	protected static $mail = null;

	public function process(ProcessingQueue $item)
	{
		if (static::$mail === null) {
			static::$mail = new Mail();
		}

		$templateTypesConfig = \EmailDeliveryConfig::get('templateTypes');
		$templateType = $item->data['templateType'];

		if (!isset($templateTypesConfig[$templateType])) {
			throw new \Exception("Email template type '$templateType' not found.", 500);
		}

		$templateConfig = $templateTypesConfig[$templateType];
		$templateRenderAction = $templateConfig['action'];
		$templateParams = $item->data['templateParams'];

		$response = $this->action($templateRenderAction, $templateParams, '', true, true);

		$fromEmail = $response->get('from') ? $response->get('from') : $templateConfig['defaultAddressFrom'];

		static::$mail->from = $fromEmail;
		static::$mail->to = $response->get('to');
		static::$mail->subject = $response->get('title');
		static::$mail->content = (string)$response;

		$success = true;
		try {
			static::$mail->send();
		} catch (\Exception $ex) {
			$success = false;
		}

		return $success;
	}
}